package 算法.leetcode.bytedance.字符串;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lchenglong
 * @date 2023/2/9
 */
public class 无重复最长子串 {
    public static  class Solution {

        public static void main(String[] args) {
            String s = "ab";
            Solution solution = new Solution();
            int length = solution.lengthOfLongestSubstring(s);
            System.out.println("无重复最长子串为:" + length);
        }
        public int lengthOfLongestSubstring(String s) {
            // 边界条件
            if (s==null||s.length() ==0)return 0;
            if (s.length()==1)return 1;
            // 定义一个访问记录
            Map<Character,Integer> visited = new HashMap<>();
            // 遍历字符串
            int max = 0,start=0;
            for (int i=0;i<s.length();i++){
                // 如果不存在就放入访问记录
                Integer index = visited.get(s.charAt(i));
                if (index != null){
                    // 之前存在过,
                    // 选一个新的无重复子串的起点
                    start = Math.max(index+1,start);
                }
                visited.put(s.charAt(i),i);
                max = Math.max(i-start+1,max);
            }
            return max;

        }
    }
}
